package cn.javadog.algorithm.m1_100;


import java.util.Objects;

/**
 * 两数相加
 * https://leetcode-cn.com/problems/add-two-numbers/
 * @author Sprite
 */
public class Algorithm2 {
	public static void main(String[] args) {
		ListNode l1 = new ListNode(5);

		ListNode l2 = new ListNode(5);

		ListNode l3 = addTwoNumbers(l1, l2);
		System.out.println(l3);
	}


	public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
		int val = l1.val + l2.val;
		int _val = val%10;
		int lt = val/10;
		ListNode node = new ListNode(_val);
		ListNode temp = node;
		while (Objects.nonNull(l1.next) && Objects.nonNull(l2.next)){
			l1 = l1.next;
			l2 = l2.next;
			val = l1.val + l2.val + lt;
			_val = val%10;
			lt = val/10;
			ListNode next = new ListNode(_val);
			temp.next = next;
			temp = next;
		}

		ListNode last = null;
		if (Objects.nonNull(l1.next)){
			last = l1;
		}else if (Objects.nonNull(l2.next)){
			last = l2;
		}

		if (Objects.nonNull(last)){
			while (Objects.nonNull(last.next)){
				last = last.next;
				val = last.val + lt;
				_val = val%10;
				lt = val/10;
				ListNode next = new ListNode(_val);
				temp.next = next;
				temp = next;
			}
		}


		if (lt > 0) {
			ListNode next = new ListNode(lt);
			temp.next = next;
		}

		return node;
	}

	protected static class ListNode {
		int val;
		ListNode next;
		ListNode(int x) {
			val = x;
		}
	}
}
